package LeetCode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LC_599_MinimumIndexSumofTwoLists {

    public static void main(String[] args) {

    }

    class Solution {
        public String[] findRestaurant(String[] list1, String[] list2) {
            List<String> minRes = null;
            Map<String, Integer> map1 = new HashMap<>();
            Map<String, Integer> map2 = new HashMap<>();
            int min = Integer.MAX_VALUE;
            for (int i = 0; i < list1.length; i++) map1.put(list1[i], i);
            for (int i = 0; i < list2.length; i++) map2.put(list2[i], i);
            for (String aList1 : list1) {
                if (map2.containsKey(aList1)) {
                    int sum = map1.get(aList1) + map2.get(aList1);
                    if (sum < min) {
                        min = sum;
                        minRes = new ArrayList<>();
                        minRes.add(aList1);
                    } else if (sum == min) {
                        minRes.add(aList1);
                    }
                }
            }
            String[] strRes = new String[minRes.size()];
            for (int i = 0; i < minRes.size(); i++) {
                strRes[i] = minRes.get(i);
            }
            return strRes;
        }
    }

    public class Solution_2 {
        public String[] findRestaurant(String[] list1, String[] list2) {
            Map<String, Integer> data = new HashMap<>();
            int min = Integer.MAX_VALUE;
            for (int i = 0; i < list1.length; ++i)
                data.put(list1[i], i);
            List<String> re = new ArrayList<>();
            for (int i = 0; i < list2.length; ++i) {
                String temp = list2[i];
                if (data.containsKey(temp)) {
                    int sum = i + data.get(temp);
                    if (sum < min) {
                        min = sum;
                        re = new ArrayList<>();
                        re.add(temp);
                    } else if (sum == min)
                        re.add(temp);
                }
            }
            return re.toArray(new String[re.size()]);
        }
        
    }
}